package org.homs.continuations;

import org.homs.jsunit.runner.RhinoRunner;
import org.homs.jsunit.runner.Runner;
import org.mozilla.javascript.NativeObject;

public class FlowController {

	protected Runner runner;
	protected String flowName;

	public FlowController(final String flowName, final String[] initScripts) {
		super();
		this.flowName = flowName;
		this.runner = new RhinoRunner();

		for (final String script : initScripts) {
			runner.evalScript(script);
		}
	}

	public Fumanchou action(final Fumanchou fumanchou) {
		final Fumanchou f;
		if (fumanchou == null) {
			f = new Fumanchou();
		} else {
			f = fumanchou;
		}
		return restartContinuation(this.flowName, f);
	}

	private Fumanchou restartContinuation(final String flowFunc, final Fumanchou f) {
		runner.put("r", f.getAsNativeObject());
		runner.eval("println(toString(r));");
		runner.eval("r = ccontinue(" + flowFunc + ", r);");
		return new Fumanchou((NativeObject) runner.get("r"));
	}

	public void close() {
		this.runner.close();
	}

}
